#include "client.h"

#define READ_DATA_SIZE	1024
#define MD5_SIZE		16
#define MD5_STR_LEN		(MD5_SIZE * 2)

void sendMd5(int sockfd,const char* filename){
    train_t sendTrain;
    char md5_str[MD5_STR_LEN + 1];
    unsigned char data[READ_DATA_SIZE];
	unsigned char md5_value[MD5_SIZE];
    MD5_CTX md5;

    int fd = open(filename,O_RDONLY);
    ERROR_CHECK(fd,-1,"open");
    MD5Init(&md5);
    while (1)
	{
		int ret = read(fd, data, READ_DATA_SIZE);
		if (ret == -1)
		{
			perror("read");
			close(fd);
		}
		MD5Update(&md5, data, ret);
		if (ret == 0 || ret < READ_DATA_SIZE)
		{
			break;
		}
	}
    close(fd);

    MD5Final(&md5, md5_value);
    for(int i = 0; i < MD5_SIZE; i++)
	{
		snprintf(md5_str + i*2, 2+1, "%02x", md5_value[i]);
	}

	sendTrain.length = strlen(md5_str);
	strcpy(sendTrain.buf,md5_str);
	send(sockfd,&sendTrain.length,sizeof(int),MSG_NOSIGNAL);
	send(sockfd,sendTrain.buf,sendTrain.length,MSG_NOSIGNAL);
}
